import os
import json
from typing import Dict, Any

class ConfigLoader:
    """安全的配置加载器，优先从环境变量读取敏感信息"""
    
    def __init__(self, config_path: str = None):
        self.config_path = config_path or os.path.join(os.path.dirname(__file__), 'config.json')
        self.config = self._load_config()
    
    def _load_config(self) -> Dict[str, Any]:
        """加载配置，优先使用环境变量"""
        # 首先加载默认配置文件
        default_config = self._load_default_config()
        
        # 使用环境变量覆盖敏感配置
        return self._override_with_env_vars(default_config)
    
    def _load_default_config(self) -> Dict[str, Any]:
        """从配置文件加载默认配置"""
        try:
            with open(self.config_path, 'r', encoding='utf-8') as f:
                return json.load(f)
        except (FileNotFoundError, json.JSONDecodeError) as e:
            print(f"警告: 无法加载配置文件 {self.config_path}: {e}")
            return self._get_fallback_config()
    
    def _override_with_env_vars(self, config: Dict[str, Any]) -> Dict[str, Any]:
        """使用环境变量覆盖敏感配置"""
        # DeepSeek API配置
        if 'deepseek_api' in config:
            if os.getenv('DEEPSEEK_API_KEY'):
                config['deepseek_api']['api_key'] = os.getenv('DEEPSEEK_API_KEY')
            if os.getenv('DEEPSEEK_BASE_URL'):
                config['deepseek_api']['base_url'] = os.getenv('DEEPSEEK_BASE_URL')
            if os.getenv('DEEPSEEK_MODEL'):
                config['deepseek_api']['model'] = os.getenv('DEEPSEEK_MODEL')
        
        # 应用配置
        if os.getenv('FLASK_PORT'):
            config['app_port'] = int(os.getenv('FLASK_PORT'))
        
        return config
    
    def _get_fallback_config(self) -> Dict[str, Any]:
        """获取回退配置"""
        return {
            "deepseek_api": {
                "api_key": os.getenv('DEEPSEEK_API_KEY', ''),
                "base_url": os.getenv('DEEPSEEK_BASE_URL', 'https://api.deepseek.com/v1'),
                "model": os.getenv('DEEPSEEK_MODEL', 'deepseek-chat'),
                "temperature": 0.7,
                "max_tokens": 2000
            },
            "weibo": {
                "max_trending_items": 20,
                "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
            },
            "article": {
                "min_length": 800,
                "max_length": 1200,
                "preferred_categories": ["娱乐", "社会", "时事"],
                "discouraged_categories": ["广告", "推广"]
            }
        }
    
    def get(self, key: str, default=None) -> Any:
        """获取配置值"""
        keys = key.split('.')
        value = self.config
        
        for k in keys:
            if isinstance(value, dict) and k in value:
                value = value[k]
            else:
                return default
        
        return value
    
    def validate_config(self) -> bool:
        """验证配置是否完整"""
        required_fields = [
            'deepseek_api.api_key',
            'deepseek_api.base_url'
        ]
        
        for field in required_fields:
            if not self.get(field):
                print(f"配置验证失败: 缺少必需的配置项 {field}")
                return False
        
        # 检查API密钥格式
        api_key = self.get('deepseek_api.api_key')
        if api_key and (api_key == 'your_key' or len(api_key) < 10):
            print("警告: API密钥可能未正确配置")
        
        return True
    
    def print_safe_config(self):
        """打印安全的配置信息（隐藏敏感信息）"""
        safe_config = self.config.copy()
        
        # 隐藏敏感信息
        if 'deepseek_api' in safe_config and 'api_key' in safe_config['deepseek_api']:
            api_key = safe_config['deepseek_api']['api_key']
            if api_key:
                safe_config['deepseek_api']['api_key'] = f"{api_key[:4]}...{api_key[-4:]}" if len(api_key) > 8 else "***"
        
        print("当前配置 (敏感信息已隐藏):")
        print(json.dumps(safe_config, indent=2, ensure_ascii=False))


# 全局配置实例
_config_loader = None

def get_config_loader(config_path: str = None) -> ConfigLoader:
    """获取配置加载器单例"""
    global _config_loader
    if _config_loader is None:
        _config_loader = ConfigLoader(config_path)
    return _config_loader

def get_config(key: str, default=None) -> Any:
    """便捷函数：获取配置值"""
    return get_config_loader().get(key, default)


if __name__ == "__main__":
    # 测试配置加载器
    loader = get_config_loader()
    loader.print_safe_config()
    
    if loader.validate_config():
        print("配置验证通过")
    else:
        print("配置验证失败，请检查环境变量和配置文件")
